class AsyncPool {

    constructor(maxConcurrency) {
        this.concurrency = 0
        this.taskQueue = []
        this.maxConcurrency = maxConcurrency || 1
    }

    async execute(task) {
        if (this.concurrency < this.maxConcurrency) {
            await this.run(task)
        } else {
            this.addTask(task)
        }
    }

    addTask(task) {
        this.taskQueue.push(task)
    }

    async run(t) {
        this.concurrency++
        await t()
        while (this.taskQueue.length > 0) {
            let task = this.taskQueue.shift()
            await task()
        }
        this.concurrency--
    }
}

const asyncPool = new AsyncPool()

export default asyncPool